Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

var record_start = 0; 

var sm = new Ext.grid.CheckboxSelectionModel();
var cm=new Ext.grid.ColumnModel([ 
sm,
new Ext.grid.RowNumberer({header: "编号",
width:40, 
renderer:function(value,metadata,record,rowIndex){ 
return record_start + 1 + rowIndex; 
} 
}),
{header:'客户ID',dataIndex:'custId',hidden:true},
{header:'客户名称',dataIndex:'custName',width:100},
{header:'单位所属行业',dataIndex:'industry',width:100}, 
{header:'信用评级',dataIndex:'creditLevel',width:100},
{header:'风险暴露分类',dataIndex:'exposureType',width:100},
{header:'违约状态',dataIndex:'defaultSta',width:100,hidden:true},
{header:'经办人',dataIndex:'inputUserId',width:100},
{header:'经办机构',dataIndex:'inputOrgId',width:100},
]); 
var ds=new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'customer/listRetailCustomer.do',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ 
totalProperty:'total',  
root:'customer'},[
{name:'custId'}, 
{name:'custName'},  
{name:'industry'},  
{name:'creditLevel'},
{name:'balance'},  
{name:'exposureType'},
{name:'defaultSta'},
{name:'inputUserId'},  
{name:'inputOrgId'}
]) 
}); 

var conditionStore = new Ext.data.SimpleStore({
	   fields : ['id', 'text'],
	   data : [['custId', '客户编号'], ['custName', '客户名称']]
	});

var grid=new Ext.grid.GridPanel({ 
id:'myCustomers',
renderTo:"customer_list", 
stripeRows:true,//斑马线效果
title:"客户列表-零售客户", 
height:500, 
cm:cm,
store: ds, 
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },   
            bbar: new Ext.PagingToolbar({   
                pageSize: 20,   
                store: ds,   
                displayInfo: true,   
                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
                emptyMsg: "没有数据" ,
                doLoad : function(start){ 
   record_start = start; 
var o = {}, pn = this.getParams(); 
          o[pn.start] = start; 
          o[pn.limit] = this.pageSize; 
this.store.load({params:o}); 
     }  
            }),
 tbar: [
 {text:'新增',id: 'btnAdd'},
        '-',       
 {text:'查看/编辑',handler:checkMyCustomer},
 '-',
 {text:'删除',handler:deleteCustomer},   
 '-',
 {text:'移交',id:'transfer',handler:transfer,}, 
 '->',
 {xtype:'combo',
 id:'condition',
 name: 'condition', 
 store: conditionStore,
 fieldLabel: '请选择查询条件',
 valueField : 'id',
 displayField : 'text',
 emptyText : '请选择查询条件',
 triggerAction : 'all',
 editable: false,
 mode:'local',
 width:110
 },'',
 {xtype:'textfield',id:'keyword',width:180},
 {text:'查询',handler:findCustomer},
 '-',
 {text:'清空',handler: callBack} ]   
});
ds.load({params:{start:0,limit:20}}); 



function findCustomer(){

var condition = Ext.getCmp('condition').getValue();
var keyword = Ext.getCmp('keyword').getValue();

if(condition == '' || condition == null){
Ext.Msg.alert('提示', '请选择查询条件！'); 
}
else{

ds.baseParams={condition:condition, keyword: keyword};
ds.proxy = new Ext.data.HttpProxy({
				url:'customer/findIndCustomer.do',
				method:'POST'
			}); 
ds.reader = new Ext.data.JsonReader({ 
					totalProperty:'total',  
					root:'resultData'},[ 
					{name:'custId', mapping: 'custId'}, 
					{name:'custName', mapping: 'custName'},  
					{name:'industry', mapping: 'industry'},
					{name:'exposureType', mapping: 'exposureType'},
					{name:'creditLevel',mapping:'creditLevel'},
					{name:'inputUserName', mapping:'inputUserId'},
					{name:'inputOrgName', mapping:'inputOrgId'},
				]);
				   
ds.load({params:{start:0,limit:20}});
record_start = 0;  	
}
}

function callBack(){

Ext.getCmp('condition').clearValue();
Ext.getCmp('keyword').setValue('');
ds.proxy = new Ext.data.HttpProxy({
				url:'customer/listRetailCustomer.do',
				method:'POST'
			}); 
ds.reader = new Ext.data.JsonReader({ 
					totalProperty:'total',  
					root:'customer'},[
										{name:'custId', mapping: 'custId'}, 
										{name:'custName', mapping: 'custName'},  
										{name:'industry', mapping: 'industry'},
										{name:'exposureType', mapping: 'exposureType'},
										{name:'creditLevel',mapping:'creditLevel'},
										{name:'inputUserName', mapping:'inputUserId'},
										{name:'inputOrgName', mapping:'inputOrgId'},
				]);   
ds.load({params:{start:0,limit:20}});
record_start = 0;
}

var addCustTypeStore=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'showType.do?type=CertType',
	method:'GET'
	}), 
	reader:new Ext.data.JsonReader({ },[
	{name:'name'}, 
	{name:'code'}
	]) ,
	autoLoad:true
}); 

//新增客户表单
addForm = new Ext.form.FormPanel({ 
id: 'addCustomerForm', 
width: 410, 
height: 220, 
//样式 
bodyStyle: 'margin:3px 3px 3px 3px', 
frame: true, 
xtype: 'filedset', 
labelWidth: 80, 
items: 
[ { xtype: 'fieldset', 
title: '客户信息', 
collapsible: true, 
autoHeight: true, 
autoWidth: true, 
items: 
[ { 
	xtype: 'textfield', 
	id:'custName',
	name: 'custName', 
	fieldLabel: '客户名称', 
	emptyText: '必填', 
	blankText: '角色名称不能为空', 
	allowBlank: false, 
    width: 250,
	maxLength: 10, 
	maxLengthText: '角色不能超过10个字符', 
	anchor: '98%' 
	}, 
	{ 
		xtype: 'textfield', 
		id:'custNo',
		name: 'custNo', 
		fieldLabel: '客户号', 
//		emptyText: '必填', 
//		blankText: '客户号号不能为空', 
//		allowBlank: false, 
        width: 250,
		maxLength: 40, 
		maxLengthText: '客户号不能超过40个字符', 
		anchor: '98%' 
		}, 
		{ 
xtype: 'combo', 
 	id : "idtype",
              store :addCustTypeStore,
              fieldLabel: '证件类型',
              valueField : 'code',
              displayField : 'name',
              typeAhead : true,
              allowBlank: false, 
              width: 250,
              mode:'remote', 
              emptyText : '请选择证件类型...',
              editable: false,
              triggerAction : 'all',
              selectOnFocus : true,
              hiddenName:'idtype'
}, { 
xtype: 'textfield', 
id: 'idno',
name: 'idno', 
fieldLabel: '证件号码', 
emptyText: '必填', 
blankText: '证件号码不能为空', 
allowBlank: false,  
width: 250,
maxLength:18,//最多字符设置
maxLengthText:'最多可输入18个字符',      //当输入大于最多字符设置时，提示信息
anchor: '98%' 
},{xtype:'hidden',
id:'CustType',
name:'CustType',
value:'04'
}
] 
}]
});

//新增用户窗口 
addWin = new Ext.Window({ 
id: 'addCustomerWin', 
title: '新增客户-零售客户', 
width: 440, 
height: 230, 
//背景遮罩 
modal: true, 
//重置大小 
resizable: false, 
//当关闭按钮被点击时执行的动作 
closeAction: 'hide', 
plain: true, 
buttonAlign: 'right', 
items:addForm, 
buttons: 
[  
{ text: '提交', id: 'btnSubmit' } ,
{ text: '关闭', handler: function() { Ext.getCmp('addCustomerWin').hide(); } }

] 
});

function addRoleFunction() {
var custName = Ext.getCmp('custName').getValue();
var custNo = Ext.getCmp('custNo').getValue();
var idtype = Ext.getCmp('idtype').getValue(); 
var idno = Ext.getCmp('idno').getValue();

if(addForm.form.isValid()){
Ext.Ajax.request({
  url:'customer/checkRetailCustomer.do',
   params : {CustName : custName,CustNo:custNo,idType:idtype,idNo:idno},
  method:'GET',
  success:function(response){
 // alert(response.responseText);
 var isExit = response.responseText;
 if (isExit==1){
 Ext.MessageBox.alert("提示","当前客户已存在，请重新输入！");
 }
 else if (isExit == 0){
 var addForm = Ext.getCmp("addCustomerForm");
 var addCustForm=addForm.getForm().getEl().dom;
 addCustForm.action = 'customer/addRetailMain.do?';
 addCustForm.method = 'POST';
 addCustForm.submit();

 }
   // window.location.href="view/customer/CheckCustomer_General.jsp";
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
});  
}
 }

//添加按钮单击事件 
function btnAddClick() { 
Ext.getCmp('addCustomerForm').form.reset(); 
Ext.getCmp("addCustomerWin").setTitle('新增客户-零售客户'); 
Ext.getCmp("addCustomerWin").buttons[0].handler = addRoleFunction; 
Ext.getCmp("addCustomerWin").show(); 
}; 

//新增按钮 
var addUserBtn = Ext.getCmp('btnAdd'); 
addUserBtn.on('click', btnAddClick); 

//删除客户
function deleteCustomer(){
var grid = Ext.getCmp('myCustomers'); 
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要删除的客户"); 
} 
else{
Ext.MessageBox.confirm('提示', '确实要删除所选的客户吗？', deleteConfirm);
}
}

function deleteConfirm(btn){
if (btn == 'yes') {
 Ext.Ajax.request({
  url:'customer/deleteCustomer.do',
  params : {CustId : grid.getSelectionModel().getSelections()[0].data.custId},
  method:'POST',
  success:function(){
   Ext.MessageBox.alert("提示","删除成功！");
   Ext.getCmp('myCustomers').store.reload(); 
  },failure:function(){
    Ext.MessageBox.alert("提示", "删除失败！"); 
  }
});
}
}

function checkMyCustomer(){
if (grid.getSelectionModel().getSelections()[0] == undefined) { 
Ext.Msg.alert("提示", "请选中要查看的客户！"); 
}
else{
	var selectedCustId = grid.getSelectionModel().getSelections()[0].data.custId;
           Ext.Ajax.request({
  url:'checkRequest.do',
  method:'GET',
  success:function(){
  window.location.href="customer/checkIndCustomer.do?CustId="+selectedCustId;
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
}); 
}
}

function rowdblclickFn(grid, rowIndex, e){//双击事件  
             var row = grid.getStore().getAt(rowIndex); 
             var selectedCustId = row.get("custId");
             Ext.Ajax.request({
  url:'checkRequest.do',
  method:'GET',
  success:function(){
  window.location.href="customer/checkIndCustomer.do?CustId="+selectedCustId;
  },failure:function(){
    Ext.MessageBox.alert("请求异常！");
  }
});  
           //  window.location.href="view/customer/CheckCustomer_General.jsp?custId="+selectedCustId;
        }   
        grid.addListener('rowdblclick',rowdblclickFn);
/*grid.on('rowdblclick',function(){ window.location.href="view/customer/CheckCustomer_General.jsp" });*/
        
        var userStore = new Ext.data.Store({ 
        	reader:new Ext.data.JsonReader({ },[
        	{name:'userCode'}, 
        	{name:'userName'}
        	]) 
        });
        
        transferForm = new Ext.form.FormPanel({ 
    		id: 'transferForm', 
    		width: 480, 
    		height: 200, 
    		//样式 
    		bodyStyle: 'margin:auto;padding:auto;', 
    		frame: true, 
    		xtype: 'filedset', 
    		labelWidth: 100, 
    		items: 
    		[ { xtype: 'fieldset',  
    		collapsible: true, 
    		autoHeight: true, 
    		autoWidth: true, 
    		items: 
    		[ 
    		 		{ layout : "form",
    		           items : [{
    		        	   xtype: 'combo',
    						id: 'transferOrg',
    						//name: 'belongorg', 
    						fieldLabel: '转移至机构', 
    						store:new Ext.data.SimpleStore({fields:['id', 'text'],data:[[]]}), 
    						displayField: 'id',
    						valueField: 'text',
    						hiddenName: 'transferOrg',
    			            editable:false, 
    			            mode: 'local', 
    			            triggerAction:'all', 
    			            frame:true,
    			            border:true,
    			            width:250,
    			            tpl: '<div id="treePanel2" style="height:180px;width:240px;"></div>', //html代码           
    			            //autoWidth:true,
    			            //autoHeight:true, 
    			            emptyText:'清选择所属机构...',
    			            resizable:true
    		           }]},
    		           
    		           { layout : "form",
    			           items : [{
    			        	  xtype: 'combo', 
    			        	  id : "transferUser",
    			              store :userStore,
    			              fieldLabel: '',
    			              valueField : 'userCode',
    			              displayField : 'userName',
    			              fieldLabel: '转移至用户', 
    			              emptyText : '请选择用户...',
    			              editable: false,
    			              typeAhead : true,
    			              width: 250,
    			              mode:'remote',  
    			              triggerAction : 'all',
    			              selectOnFocus : true,
    			              hiddenName:'transferUser'
    			     }]},
    		]}]});

      //转移窗口 
		transferWin = new Ext.Window({
		id: 'transferWin', 
		title: '人员信息', 
		width: 500, 
		height: 220, 
		//背景遮罩 
		modal: true, 
		//重置大小 
		resizable: false, 
		//当关闭按钮被点击时执行的动作 
		closeAction: 'hide', 
		plain: true, 
		buttonAlign: 'right', 
		items:transferForm, 
		buttons: 
		[  
		{ text: '转移', id: 'btnSubmit1' } ,
		{ text: '关闭', handler: function() { Ext.getCmp('transferWin').hide(); } }
		] 
		});
		
        var tree2 = new Ext.tree.TreePanel
        ({ 
            animate:true,
            titleCollapse:true,
            root:root2,
            singleExpand:false,
            iconCls:"icon-tree",
            autoLoad:false,
            allowDomMove:true,
            frame:true,
            collapsible:false,
            collapsed:false,
            collapseFirst:true,
            border:false,
            listeners:{ 
            	render:function(tree1){ 
            		tree1.el.on('click',function(e){ 
        			e.stopPropagation(); }) ;
        		} 
        	} 
        });

        var loader2=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

        var root2=new Ext.tree.AsyncTreeNode
        ({
         id:"0", 
         leaf:false,
         loader: loader2,
         text:"清远农商行总行",
         expandable:true,
         expanded:true 
        });         

        tree2.setRootNode(root2);

        var comboTree2 =  Ext.getCmp('transferOrg');      
        var orgCode2 = "";
        comboTree2.on('expand',function(){tree2.render('treePanel2');});

        var tree_click = function(node,e)
        {
        	 e.stopEvent();   //非叶子节点则不触发
             comboTree2.setValue(node.id);  //设置option值
             comboTree2.setRawValue(node.text);
             //comboTree.hiddenField.value = node.id;  
         	comboTree2.collapse();   //隐藏option列表
//         	alert(comboTree.value);
//         	alert(comboTree.getValue());
//         	alert(comboTree.getRawValue());
         	//alert(comboTree.value);
         	orgCode2 = comboTree2.value;
         	
         	
         	var transferUser = Ext.getCmp('transferUser');
        		transferUser.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
//        		 alert(combo.value);
        		//alert(orgCode2);
        		//alert(userId);
        		userStore.proxy =new Ext.data.HttpProxy({
        				url:'showUser.do?orgCode='+orgCode2,
        				method:'GET'
        		});
        		userStore.load(); //加载下拉框的store   
        };
        tree2.on("click",tree_click);  
        		
         		
		
		function transfer(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要查看的项！"); 
			}else{
				custId = grid.getSelectionModel().getSelections()[0].data.custId;
				
				//alert(grid.getSelectionModel().getSelections()[0].data.userId);
				
				Ext.getCmp('transferForm').form.reset();
				//Ext.getCmp('password').setValue('0000000000');
				Ext.getCmp("transferWin").buttons[0].handler = transferFunction; 
				Ext.getCmp("transferWin").show();
			}
		}

		//移交
		function transferFunction(){
			
			var transferForm = Ext.getCmp("transferForm");
		if(transferForm.form.isValid()){
			transferForm.form.doAction('submit', { 

		                    url : 'system/transferCustomer.do', 
		                    params : { custId: grid.getSelectionModel().getSelections()[0].data.custId},
		                    method : 'post', 
		 
		                       
		                       success : function() { 

		                       
		                       grid.store.reload();
		                       Ext.Msg.alert('提示', '转移成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 

		                           Ext.Msg.alert('提示', '转移失败！'); 
		 
		                        } 
		                    }); 
		                    }
		}
		
		if(document.getElementById("roleName").innerHTML.indexOf("超级管理员") >= 0){
			Ext.getCmp('transfer').show();
		}
		else{
			Ext.getCmp('transfer').hide();
		}
}); 